﻿using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

using ipi.MCC.Global;
using ipi.MCC.Controls;

namespace ipi.MCC.WebParts
{
    [Guid("cb455a6e-c0d9-4085-ba54-21b3af808595")]
    public class MCCDocumentView : MCCAjaxBaseWebPart
    {
        protected MCCDocumentViewControl ucDocumentView;
        protected CustomValidator validGlobal;

        private int _SelectedNode
        {
            get
            {
                int iReturn = -1;
                if(ViewState["MCCDocumentView_SelectedNode"] != null)
                {
                    iReturn = Convert.ToInt32(ViewState["MCCDocumentView_SelectedNode"]);
                }

                return iReturn;
            }
            
            set
            {
                if(!value.Equals(-1))
                {
                    if (ViewState["MCCDocumentView_SelectedNode"] != null)
                    {
                        ViewState["MCCDocumentView_SelectedNode"] = value;
                    }
                    else
                    {
                        ViewState.Add("MCCDocumentView_SelectedNode", value);
                    }
                }
            }
        }

        private int _PagingCount = 50;
        private bool _EnablePaging;
        
        [WebDescription(""), WebDisplayName("Page count"), Personalizable(PersonalizationScope.User), WebBrowsable(true)]
        public int PagingCount
        {
            get { return _PagingCount; }
            set { _PagingCount = value; }
        }

        [WebDescription(""), WebDisplayName("Enable paging"), Personalizable(PersonalizationScope.User), WebBrowsable(true)]
        public bool EnablePaging
        {
            get { return _EnablePaging; }
            set { _EnablePaging = value; }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            // TODO: add custom rendering code here.
            // writer.Write("Output HTML");

            EnsureChildControls();

            // The appropriate child control will render based on what was added to the collection
            try
            {
                RenderChildren(writer);
            }
            catch (System.Exception exc)
            {
                writer.WriteLine("The following error occurred in this Web Part.  Please contact your administrator for further assistance. \n" + Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Global_Exception));
            }
        }

        protected override void CreateChildControls()
        {
            this.Controls.Clear();
            validGlobal = new CustomValidator();
            validGlobal.Display = ValidatorDisplay.Dynamic;
            this.Controls.Add(validGlobal);
            
            try
            {                
                ucDocumentView = new MCCDocumentViewControl();
                ucDocumentView.PagingCount = _PagingCount;
                ucDocumentView.EnablePaging = _EnablePaging;
                if (_SelectedNode == -1 && this.Page.Request.QueryString["Path"] != null)
                {
                    SPSite spsCurrent = SPContext.Current.Site;
                    WebSettings wsCurrent = new WebSettings(spsCurrent);

                    using (SPSite spsRoot = new SPSite(!string.IsNullOrEmpty(wsCurrent.MasterWebURL) ? wsCurrent.MasterWebURL : spsCurrent.Url))
                    {
                        SPWeb spwRoot = spsRoot.RootWeb;
                        SPList splNodes = Functions.GetTreeList(spwRoot);
                        _SelectedNode = GetQueryNode(splNodes, this.Page.Request.QueryString["Path"]);
                    }                                        
                }
                ucDocumentView.SetSelectedNode(_SelectedNode);
                
                this.Controls.Add(ucDocumentView);
            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = exc.Message;
                validGlobal.IsValid = false;
            }
        }

        private int GetQueryNode(SPList splNodes, string querystring)
        {
            return Functions.GetNodeIdForExpand(splNodes, querystring, "/");
        }


        [ConnectionConsumer("Node Consumer")]
        public void GetConnectionInterface(IMCCSelectNode SelectedNode)
        {
            if (SelectedNode != null)
            {
                if (ucDocumentView == null)
                {
                    _SelectedNode = SelectedNode.GetNodeID;
                }
                else
                {
                    _SelectedNode = SelectedNode.GetNodeID;
                    ucDocumentView.SetSelectedNode(_SelectedNode);
                }
            }
        }
    }
}
